// pages/purchase-list/purchase-list.js
const app = getApp();

Page({
    data: {
        orderId: '',
        orderData: null,
        purchaseList: [],
        progress: 0,
        completedCount: 0,
        totalCount: 0
    },

    onLoad: function(options) {
        const orderId = options.orderId;
        console.log("接收到的订单ID:", orderId, "类型:", typeof orderId);
        
        // 根据orderId获取订单数据
        const orderData = this.getOrderData(orderId);
        
        if (!orderData) {
            wx.showToast({
                title: '未找到订单数据',
                icon: 'none'
            });
            return;
        }
        
        // 生成采购清单
        const purchaseList = this.generatePurchaseList(orderData);
        
        this.setData({
            orderId: orderId,
            orderData: orderData,
            purchaseList: purchaseList,
            totalCount: purchaseList.length
        });
        
        this.calculateProgress();
    },

    // 获取订单数据
    getOrderData: function(orderId) {
        try {
            const orders = wx.getStorageSync('orders') || [];
            console.log('所有订单:', orders);
            console.log('要查找的订单ID:', orderId, '类型:', typeof orderId);
            
            // 尝试多种方式匹配订单ID
            const order = orders.find(order => {
                // 转换为字符串比较，避免类型不一致
                return String(order.id) === String(orderId);
            });
            
            console.log('找到的订单:', order);
            return order;
        } catch (error) {
            console.error('获取订单数据失败:', error);
            return null;
        }
    },

    // 生成采购清单
    generatePurchaseList: function(orderData) {
        if (!orderData || !orderData.items) {
            console.log('订单数据为空或没有菜品');
            return [];
        }
        
        console.log('订单中的菜品:', orderData.items);
        
        const ingredientMap = {};
        
        // 菜品数据
        const dishesData = [
            { id: 'chef1', name: '蒜香鱼片', ingredients: '黑鱼片，泡椒，蒜' },
            { id: 'chef2', name: '茭白肉丝', ingredients: '茭白，肉丝，榨菜，青椒' },
            { id: 'chef3', name: '韭黄炒蛋', ingredients: '鸡蛋，韭黄' },
            { id: 'chef4', name: '清炒绿豆芽', ingredients: '绿豆芽' },
            { id: 'chef5', name: '清炒牛心菜', ingredients: '牛心菜，大蒜' },
            { id: 'chef6', name: '丝瓜炒蛋', ingredients: '丝瓜，鸡蛋' },
            { id: 'chef7', name: '水面筋炒鸡腿菇', ingredients: '青椒，水面筋，杏鲍菇，香油' },
            { id: 'chef8', name: '洋葱肉丝', ingredients: '猪肉丝，洋葱' },
            { id: 'chef9', name: '韭菜花炒肉丝', ingredients: '韭菜花，梅花肉' },
            { id: 'staple1', name: '葱油芋艿', ingredients: '芋艿，香葱' },
            { id: 'stirfry1', name: '干香焗大黄鱼', ingredients: '大黄鱼，葱姜蒜，洋葱，小米椒' },
            { id: 'stirfry2', name: '干蒸罗氏虾', ingredients: '罗氏虾' },
            { id: 'stew1', name: '花生酱牛尾', ingredients: '牛尾/牛T骨，洋葱' },
            { id: 'stew2', name: '口蘑炒肉', ingredients: '口蘑，猪梅花肉' },
            { id: 'stew3', name: '排骨黄鱼汤', ingredients: '黄鱼，软骨肋排，娃娃菜，肉丸，鱼丸，油豆腐' },
            { id: 'stew4', name: '酸菜牛肉', ingredients: '酸菜，牛里脊（谷饲）' },
            { id: 'stew5', name: '红烧羊肉', ingredients: '羊肉，八角，香叶，干辣椒，花椒' },
            { id: 'drink1', name: '牛奶咖啡', ingredients: '牛奶，白砂糖，Moccona咖啡冻干' }
        ];
        
        // 遍历订单中的每个菜品
        orderData.items.forEach(dish => {
            console.log('处理菜品:', dish);
            
            // 查找菜品数据
            const dishInfo = dishesData.find(d => d.id === dish.id);
            if (!dishInfo) {
                console.log('未找到菜品信息:', dish.id);
                return;
            }
            
            if (!dishInfo.ingredients) {
                console.log('菜品没有食材信息:', dishInfo.name);
                return;
            }
            
            console.log('找到菜品信息:', dishInfo);
            
            // 分割食材字符串 - 使用中文逗号
            const ingredients = dishInfo.ingredients.split('，');
            console.log('食材列表:', ingredients);
            
            // 处理每个食材
            ingredients.forEach(ing => {
                const ingredientName = ing.trim();
                if (!ingredientName) return;
                
                if (ingredientMap[ingredientName]) {
                    // 如果食材已存在，添加来源菜品
                    if (!ingredientMap[ingredientName].fromDishes.includes(dishInfo.name)) {
                        ingredientMap[ingredientName].fromDishes.push(dishInfo.name);
                    }
                } else {
                    // 新食材
                    ingredientMap[ingredientName] = {
                        name: ingredientName,
                        purchased: false,
                        fromDishes: [dishInfo.name]
                    };
                }
            });
        });
        
        const result = Object.values(ingredientMap);
        console.log('生成的采购清单:', result);
        return result;
    },

    // 切换食材采购状态
    toggleItem: function(e) {
      const selectList = e.detail.value || [];
      console.log(selectList);
      var currettPageList = this.data.purchaseList;
      currettPageList.forEach(item => {
        if (selectList.includes(item.name)) {
          item.purchased = true;
        } else {
          item.purchased = false;
        }
      })

        // const index = e.currentTarget.dataset.index; // 获取索引
        // const purchased = e.detail.value.length > 0; // 根据checkbox的选择状态
    
        // const key = `purchaseList[${index}].purchased`;
        
        // // 更新对应项的采购状态
        this.setData({
          purchaseList: currettPageList
        }, () => {
            // 在更新完成后计算进度
            this.calculateProgress();
        });
    },

    // 计算采购进度
    calculateProgress: function() {
        const purchasedItems = this.data.purchaseList.filter(item => item.purchased); // 过滤出已采购的食材
        const completedCount = purchasedItems.length; // 已完成的数量
        const totalCount = this.data.purchaseList.length; // 总数量
        const progress = totalCount > 0 ? Math.round((completedCount / totalCount) * 100) : 0; // 计算进度
    
        // 更新数据
        this.setData({
            progress: progress,
            completedCount: completedCount
        });
    },

    // 返回上一页
    goBack: function() {
        wx.navigateBack();
    }
});